package cloud.daodao.storm.security.service;

import cloud.daodao.storm.common.security.error.SecurityError;
import cloud.daodao.storm.common.security.model.aes.AesCipherData;
import cloud.daodao.storm.common.security.model.aes.AesCipherParam;
import cloud.daodao.storm.common.error.AppException;
import cloud.daodao.storm.common.util.security.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AesService {

    public AesCipherData aesEncrypt(AesCipherParam param) {
        String key = param.getKey();
        String iv = param.getIv();
        String source = param.getSource();
        String encode = param.getEncode();
        String target;
        try {
            target = AesUtil.encrypt(key, iv, source, AesUtil.Encode.valueOf(encode));
        } catch (Exception e) {
            throw new AppException(SecurityError.AES_ENCRYPT_ERROR, e);
        }
        AesCipherData data = new AesCipherData();
        data.setTarget(target);
        return data;
    }

    public AesCipherData aesDecrypt(AesCipherParam param) {
        String key = param.getKey();
        String iv = param.getIv();
        String source = param.getSource();
        String encode = param.getEncode();
        String target;
        try {
            target = AesUtil.decrypt(key, iv, source, AesUtil.Encode.valueOf(encode));
        } catch (Exception e) {
            throw new AppException(SecurityError.AES_DECRYPT_ERROR, e);
        }
        AesCipherData data = new AesCipherData();
        data.setTarget(target);
        return data;
    }

}
